package com.soecode.lyf.taglib;


import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import com.soecode.lyf.common.SessionBean;
import com.soecode.lyf.constant.Constants;
import com.soecode.lyf.privilege.Privilege;

import java.io.IOException;
import java.util.Set;

/**
 * Created by lijie on 16/11/5.
 */
public class SecurityTagHandler extends SimpleTagSupport {

    /**
     * 需要的权限列表，逗号分隔，形如"USER_ADD, USER_ALTER"
     */
    private String privilegeString;

    public void doTag() throws JspException, IOException {

        SessionBean sb = getSessionBean();

        if (sb != null) {
        	Boolean flag = true;
            Set<Privilege> userPrivileges = sb.getPrivileges();
            String[] privileges = privilegeString.split(",");
            for (String p : privileges) {
                Privilege anEnum = Privilege.valueOf(p.trim());
                if (anEnum != null && !userPrivileges.contains(anEnum)) {
                	flag = false;
                	break;
                }
            }
            if(flag){
            	getJspBody().invoke(null);
            }
        }
    }

    private SessionBean getSessionBean() {
        JspContext jspContext = this.getJspContext();
        Object sessionBean = jspContext.getAttribute(Constants.SESSION_BEAN, PageContext.SESSION_SCOPE);
        if (sessionBean != null && sessionBean instanceof SessionBean) {
            return (SessionBean) sessionBean;
        }
        return null;
    }

	public String getPrivilegeString() {
		return privilegeString;
	}

	public void setPrivilegeString(String privilegeString) {
		this.privilegeString = privilegeString;
	}


}
